from rest_framework import serializers
from .models import Course, Student, User, Grade


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {
            'id': {'read_only': True},
        }

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        return user

    def get_image(self, obj):
        if obj.image:
            request = self.context.get('request')
            return request.build_absolute_url(obj.image.url)
        return None


class StudentSerializer(serializers.ModelSerializer):
    gender_display = serializers.SerializerMethodField()

    class Meta:
        model = Student
        fields = ['id', 'image', 'name', 'age', 'gender', 'gender_display', 'department']
        extra_kwargs = {
            'id': {'read_only': True},
            'gender': {'write_only': True},  # 只允许写入，不允许读取
        }

    @staticmethod
    def get_gender_display(obj):
        # 打印 obj.gender 的值
        # print(f"obj.gender: {obj.gender}")
        res = dict(Student.CHOICE_GENDER).get(obj.gender)
        # print(f"res: {res}")
        return res

    def to_internal_value(self, data):
        # 将前端传递的文本转换为对应的数字
        gender_text = data.get('gender_display')
        if gender_text:
            gender_dict = {v: k for k, v in Student.CHOICE_GENDER}
            data['gender_display'] = gender_dict.get(gender_text)
        return super().to_internal_value(data)


class CourseSerializer(serializers.ModelSerializer):
    create_user_username = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = ['course_id', 'course_name', 'create_user', 'create_user_username']
        extra_kwargs = {
            'course_id': {'read_only': True},
        }

    @staticmethod
    def get_create_user_username(obj):
        return obj.create_user.username


class GradeSerializer(serializers.ModelSerializer):
    # course_name = serializers.SerializerMethodField()
    # student_name = serializers.SerializerMethodField()
    course_name = serializers.CharField(source='course.course_name', read_only=True)
    student_name = serializers.CharField(source='student.name', read_only=True)

    class Meta:
        model = Grade
        fields = ['id', 'student_name', 'course_name', 'grade', 'student', 'course']
        extra_kwargs = {
            'id': {'read_only': True},
            'student': {'write_only': True},
            'course': {'write_only': True},
        }

    def to_internal_value(self, data):
        # 获取 student 和 course 对象
        student_name = data.get('student_name')
        course_name = data.get('course_name')

        if student_name:
            try:
                student = Student.objects.get(name=student_name)
                data['student'] = student.id
            except Student.DoesNotExist:
                raise serializers.ValidationError(f"Student with name {student_name} does not exist.")

        if course_name:
            try:
                course = Course.objects.get(course_name=course_name)
                data['course'] = course.course_id
            except Course.DoesNotExist:
                raise serializers.ValidationError(f"Course with name {course_name} does not exist.")

        return super().to_internal_value(data)

    def create(self, validated_data):
        # 创建 Grade 实例
        grade = Grade.objects.create(**validated_data)
        return grade

    @staticmethod
    def get_course_name(obj):
        return obj.course.course_name

    @staticmethod
    def get_student_name(obj):
        return obj.student.name
